package com.srp.backend.controller;

import com.srp.backend.common.Result;
import com.srp.backend.dto.LoginRequest;
import com.srp.backend.dto.LoginResponse;
import com.srp.backend.dto.RegisterRequest;
import com.srp.backend.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.http.ResponseEntity;

import jakarta.validation.Valid;

/**
 * 认证控制器
 */
@RestController
@RequestMapping("/api/auth")
@CrossOrigin(origins = "*")
public class AuthController {
    
    @Autowired
    private UserService userService;
    
    /**
     * 用户登录
     */
    @PostMapping("/login")
    public Result<LoginResponse> login(@Valid @RequestBody LoginRequest loginRequest) {
        try {
            LoginResponse response = userService.login(loginRequest);
            return Result.success(response);
        } catch (RuntimeException e) {
            return Result.error(e.getMessage());
        } catch (Exception e) {
            return Result.error("登录失败，请稍后重试");
        }
    }
    
    /**
     * 用户登出
     */
    @PostMapping("/logout")
    public Result<String> logout() {
        // JWT是无状态的，登出只需要前端删除token即可
        return Result.success("登出成功");
    }

    /**
     * 用户注册
     */
    @PostMapping("/register")
    public Result<String> register(@RequestBody @Valid RegisterRequest request){
        try {
            userService.register(request);
            return Result.success("注册成功");
        } catch (RuntimeException e){
            return Result.error(e.getMessage());
        } catch (Exception e){
            return Result.error("注册失败，请稍后重试");
        }
    }

}